package com.pd.modules.client.dialogs;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.AbstractButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDialog;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import com.pd.modules.client.database.DBReservationsHandler;
import com.pd.modules.client.database.Database;
import com.pd.modules.common.Reservation;
import javax.swing.JSeparator;
import javax.swing.UIManager;

@SuppressWarnings("serial")
public class DialogReservations extends JDialog implements Observer
{

	private final JPanel contentPanel = new JPanel();
	private JTable mTable;
	private DefaultTableModel mTableModel = null;
	private String[] mTableColumns = new String[] { "ID", "Sala", "Data Inicio", "Data Fim", "Username" };
	private JMenuItem mMenuItemDelete;

	private String mRoomID;
	
	private synchronized void showReservations()
	{
		DBReservationsHandler db = Database.getInstance().Reservations();
		Reservation[] tmpArray = db.getAllReservations();

		if (null == tmpArray || tmpArray.length == 0)
		{
			mTableModel = new DefaultTableModel(null, mTableColumns);
			mTable.setModel(mTableModel);
			return;
		}

		Object[][] rows = new Object[tmpArray.length][5];
		for (int i = 0; i < tmpArray.length; i++)
		{
			rows[i] = tmpArray[i].getAsTableRow();
		}

		refreshTable(rows);
	}

	private void refreshTable(Object[][] _data)
	{
		mTableModel = new DefaultTableModel(_data, mTableColumns);
		mTable.setModel(mTableModel);

		// Alinha o texto ao centro
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
		dtcr.setHorizontalAlignment(SwingConstants.CENTER);
		for (String columnName : mTableColumns)
			mTable.getColumn(columnName).setCellRenderer(dtcr);
	}

	/**
	 * Create the dialog.
	 */
	public DialogReservations(String _roomID)
	{
		mRoomID = _roomID;
		setResizable(false);
		Database.getInstance().Reservations().addObserver(this);

		setModal(true);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setTitle("Reservas da sala: " + mRoomID);
		setBounds(100, 100, 602, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JScrollPane scrollPane = new JScrollPane();
			contentPanel.add(scrollPane);
			{
				mTable = new JTable(null, mTableColumns)
				{
					@Override
					public boolean isCellEditable(int rowIndex, int colIndex)
					{
						return false; // Disallow the editing of any cell
					}
				};

				mTable.setModel(new DefaultTableModel(null, mTableColumns));
				mTable.getSelectionModel().addListSelectionListener(new EventSelectionChanged());
				mTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
				scrollPane.setViewportView(mTable);
				{
					JMenuBar menuBar = new JMenuBar();
					setJMenuBar(menuBar);
					{
						JMenu mnFicheiro = new JMenu("Ficheiro");
						menuBar.add(mnFicheiro);
						{
							mMenuItemDelete = new JMenuItem("Eliminar...");
							mMenuItemDelete.setEnabled(false);
							mMenuItemDelete.addActionListener(new ActionListener()
							{
								public void actionPerformed(ActionEvent e)
								{
									int idx = mTable.getSelectedRow();
									Integer ID = (Integer) mTable.getModel().getValueAt(idx, 0);

									// Apaga a reserva da base de dados
									Database.getInstance().Reservations().deleteReservation(ID.toString());
								}
							});
							{
								JMenuItem mMenuNew = new JMenuItem("Nova...");
								mMenuNew.addActionListener(new ActionListener() {
									public void actionPerformed(ActionEvent e) {
										DialogCreateReservation dialog = new DialogCreateReservation(mRoomID);
										dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
										dialog.setVisible(true);
									}
								});
								mnFicheiro.add(mMenuNew);
							}
							mnFicheiro.add(mMenuItemDelete);
						}
						{
							JMenuItem mntmSair = new JMenuItem("Sair");
							mntmSair.addActionListener(new ActionListener()
							{
								public void actionPerformed(ActionEvent e)
								{
									setVisible(false);
								}
							});
							{
								JSeparator separator = new JSeparator();
								separator.setForeground(UIManager.getColor("CheckBox.background"));
								mnFicheiro.add(separator);
							}
							mnFicheiro.add(mntmSair);
						}
					}
					{
						JMenu mnOpes = new JMenu("Op\u00E7\u00F5es");
						menuBar.add(mnOpes);
						{
							{
								JCheckBoxMenuItem chkFiltrar = new JCheckBoxMenuItem("Filtrar");
								chkFiltrar.addActionListener(new ActionListener()
								{
									public void actionPerformed(ActionEvent e)
									{
										AbstractButton aButton = (AbstractButton) e.getSource();
										boolean selected = aButton.getModel().isSelected();

										if (selected)
										{
											DialogDateFilter dialog = new DialogDateFilter(false);
											dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
											dialog.setVisible(true);
										} else
											Database.getInstance().Reservations().setDateFilter(null);
									}
								});
								mnOpes.add(chkFiltrar);
							}
						}
					}
				}
			}
		}
		Database.getInstance().Reservations().setRoomFilter(_roomID);
	}

	class EventSelectionChanged implements ListSelectionListener
	{

		@Override
		public void valueChanged(ListSelectionEvent e)
		{
			mMenuItemDelete.setEnabled(true);
		}
	}

	@Override
	public void update(Observable arg0, Object arg1)
	{
		showReservations();
	}
}
